package org.halo.trade.data.sina;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpRequestFutureTask;
import org.apache.log4j.Logger;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.halo.trade.data.config.Config;
import org.json.JSONObject;

public class SinaLevel2Fetcher extends Thread// implements Runnable
{
	private static Logger logger=Logger.getLogger(SinaLevel2Fetcher.class); 

	private List<String> indexsymbols = new ArrayList<>();// 指数的代码
	private List<String> symbols = new ArrayList<>();// 股票代码

	private volatile boolean toClose = false;
	private String token = null;
	private int fetch_type = 0;// 用给处理程序区分用途
	private WebSocketClient client = null;
	private SinaWebSocket socket = null;
	private Level2Handler level2_handler = null;// 处理句柄
	private long last_authen_time = 0;
	private SinaLevel2Fetcher preFecher = null;
	private int timeout = 60;// s
	private IDatatUtils datautils =new DefaultSinaDataUtilis();
	
	private String fetchName = "";
	
	public String getFetchName(){
		return this.fetchName;
	}
	
	// 2cn_sh000001=上证指数,15:09:38,2015-10-16,3338.0730,3358.2972,3393.0178,3334.8539,3391.3516,,0,395460575,459447813308.300,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
	// 2cn_sz399001=深证成指,15:05:02,2015-10-16,11229.3801,11301.9359,11384.2406,11172.0427,11374.8345,,10536012,18028363914,262517434059.370,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
	// 2cn_sh000300=沪深300,15:09:38,2015-10-16,3486.8150,3508.5177,3537.5387,3487.1044,3534.0653,,0,208964709,252211491385.800,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
	// 2cn_sz399005=中小板指,15:05:02,2015-10-16,7628.3456,7674.2905,7719.9977,7557.4572,7710.4684,,2220756,3003427123,56401124574.060,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
	// 2cn_sz399006=创业板指,15:05:02,2015-10-16,2404.5334,2424.6208,2452.9403,2401.0933,2449.0300,,1717098,2212893417,59776204792.210,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

	/**
	 * symbols:需要订阅到股票代码 
	 * indexsymbols：需要订阅到指数代码 
	 * preFecher：前一个获取level2的对象
	 */
	public SinaLevel2Fetcher(int fetch_type, List<String> symbols, List<String> indexsymbols, Level2Handler level2_handler, SinaLevel2Fetcher preFetcher)
	{
		this.fetch_type = fetch_type;
		this.symbols.clear();
		if (symbols != null)
		{
			this.symbols.addAll(symbols);
		}

		this.indexsymbols.clear();
		if (indexsymbols != null)
		{
			this.indexsymbols.addAll(indexsymbols);
		}

		this.level2_handler = level2_handler;
		this.preFecher = preFetcher;
		
		boolean isInit = this.datautils.init();
	}
    
	public boolean getToClose(){
		return this.toClose;
	}
	public boolean contains(String id)
	{
		return symbols.contains(id);
	}

	public List<String> getSymbols()
	{
		List<String> list = new ArrayList<>();
		if (symbols != null)
		{
			list.addAll(symbols);
		}
		return list;
	}

	public boolean isConnected()
	{
		if (client == null)
			return false;

		if (socket == null)
			return false;
		return socket.isConnected();
	}

	@Override
	public void run()
	{
		boolean foreAuthen = false;
		//当系统被中断或者要求关闭时，跳出循环
		while (!Thread.interrupted() && !toClose)
		{
			try
			{
				//当前时间和上次鉴权时间
				long delta = (System.currentTimeMillis() - last_authen_time) / 1000;
				//每隔20S去后台执行一次鉴权。
				if (Math.abs(delta) > timeout / 3)
				{
					String ret = getLevel2AuthenCodeInfo(symbols, indexsymbols, foreAuthen);
					//解析验证请求。
					int status = parse_KKE_Authen_Code(ret);
					switch (status) {
						case 0:
							foreAuthen = false;
							if (client != null) {
								doHearbit();
							} else {
								//启动client
								startWebSocket();
							}
							last_authen_time = System.currentTimeMillis();
							break;
	
						case -6:
							foreAuthen = true;
							last_authen_time = 0;
							break;
						case -1:// need relogin;
							 //datautils.login();
						default:
							stopWebSocket();
							Thread.sleep(3000);
							last_authen_time = 0;
					}

				}
				Thread.sleep(1000);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
				break;
			}
		}

		try
		{
			if (client != null)
				client.stop();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		logger.error("SinaLevelFectcher closed .");
	}

	private int parse_KKE_Authen_Code(String str)
	{
		if (str == null)
			return -1;

		JSONObject jsonObject = new JSONObject(str);
		String result = jsonObject.optString("result");
		int msg_code = jsonObject.optInt("msg_code");
		int timeout = jsonObject.optInt("timeout");

		if (msg_code == 1)
		{
			//如果是1，说明结果是正常的。
			this.token = result;
			this.timeout = timeout;
			return 0;
		} else if (msg_code == -6)
		{
			// 需求确认
			for (String key : jsonObject.keySet())
			{
				Object val = jsonObject.get(key);
				logger.info("[" + key + "]=" + val);
			}
			logger.info("error=========");
			return -6;
		}
		for (String key : jsonObject.keySet())
		{
			Object val = jsonObject.get(key);
			logger.info("[" + key + "]=" + val);
			logger.info("error=========");
		}
		return -2;
	}

	/**
	 * 定期要将token传输到服务器端。
	 */
	private void doHearbit()
	{
		try
		{
			socket.send(token);
		} catch (Exception e)
		{
			e.printStackTrace();
			this.stopWebSocket();
		}

	}

	public void stopWebSocket()
	{
		try
		{
//			if (client != null)
//			{
//				if(client.isRunning()){
//					client.stop();
//				}
//			}
			client = null;
			socket = null;
			last_authen_time = 0;
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void close()
	{
		//关闭预先请求
		if (preFecher != null)
		{
			preFecher.close();
		}
		//websocket已经退出了，所以这里增加重连机制。
		//toClose = true;
		//Thread.interrupted();
		//相当于系统被重置了。
		stopWebSocket();
	}
	
	public void closeThread()
	{
		this.close();
		//websocket已经退出了，所以这里增加重连机制。
		toClose = true;
		Thread.interrupted();
	}
   
	//启动websocket
	public boolean startWebSocket()
	{
		synchronized (symbols)
		{
			try
			{
				String list = Config.makeLevel2QueryString(symbols, indexsymbols,this.fetch_type);
				//获取一个数据列表
				String url = "ws://ff.sinajs.cn/wskt?token=" + token + "&list=" + list;
				URI uri = new URI(url);
				client = new WebSocketClient();
				socket = new SinaWebSocket(this);
				client.start();
				ClientUpgradeRequest request = new ClientUpgradeRequest();
				client.connect(socket, uri, request);
				return true;
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return false;
	}

	// me.stockHQ = '2cn_' + me.curStock; //实时行情
	// me.stockOrder = '2cn_' + me.curStock + '_orders'; //50笔委托单
	// me.stockZB_0 = '2cn_' + me.curStock + '_0'; //逐笔
	// me.stockZB_1 = '2cn_' + me.curStock + '_1'; //逐笔
	// me.stockInfo = me.curStock; //基本信息,（没有什么用）
	// me.stockInfoi = me.curStock + '_i'; //基本信息
	// me.lishiZB = '2cn_' + me.curStock + '_1'; //历史逐笔

	// [sys_time=1444911463]
	// [2cn_sh600650=锦江投资,15:00:00,2015-10-15,38.820,37.950,42.700,37.880,42.700,PH,56293,38369848,1576583982.610,2879979,40.910,0,0.000,15176,27551087,1125549155.970,11890,16073191,666101498.440,2196,0,10,0,42.700,42.690,42.680,42.660,42.650,42.640,42.620,42.610,42.600,42.590,1378497,4800,1600,200,1600,300,200,1200,1600,500,0.000,0.000,0.000,0.000,0.000,0.000,0.000,0.000,0.000,0.000,0,0,0,0,0,0,0,0,0,0]
	// [2cn_sh600650_orders=15:00:00.000,15:00:00.000,42.700,1378497,50,0.000,0,0,43997|1700|100|22200|2200|8200|300|3000|700|500|14200|2000|500|100|500|800|100|10000|10000|800|1000|700|300|2000|1000|700|42000|100|100|600|300|1100|15000|100|2000|2200|200|2100|1000|300|5000|1000|300|100|242400|5000|1000|3000|10000|400,,,]
	// [2cn_sh600650_0=2943013|14:59:57.510|42.700|2500|106750.000|3693493|4737159|0|5]
	// [2cn_sh600650_1=2938322|14:59:49.090|42.700|50|2135.000|3693493|4732493|0|5]
	// [sh600650_i=A,jjtz,0.3880,0.4108,0.2090,7.0005,1557.9267,55161.0107,39056.0075,39056.0075,16105.0032,CNY,2.1421,2.2670,52.0000,1,3.6400,10.6394,1.1501]

	// [sh600650=锦江投资,37.95,38.82,42.70,42.70,37.88,42.70,0.00,38369848,1576583983,1378497,42.70,4800,42.69,1600,42.68,200,42.66,1600,42.65,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,2015-10-15,15:04:12,00]
	// [2cn_sz002342=巨力索具,15:00:18,2015-10-15,6.340,6.300,6.540,6.280,6.520,PH,14865,32306319,208605766.610,4918140,6.290,7131952,6.720,3141,14829241,0.000,4206,14493975,0.000,9056,10827,10,10,6.510,6.500,6.490,6.480,6.470,6.460,6.450,6.440,6.430,6.420,461190,290650,147600,144600,65900,120000,130800,156900,111100,156500,6.520,6.530,6.540,6.550,6.560,6.570,6.580,6.590,6.600,6.610,637200,310792,397700,519600,321716,95300,424320,91500,206900,13600]
	// [2cn_sz002342_orders=15:00:18.890,15:00:18.890,6.510,461190,83,6.520,637200,107,10990|2000|1000|5000|1000|2000|3500|5100|35400|5000|10000|7400|20000|9700|80000|1100|500|800|3300|700|1000|1000|2600|300|33200|51700|40000|100|2200|5000|1000|100|3000|300|1000|800|1000|3000|1500|500|1800|2500|1000|1800|2500|300|1000|5000|300|1300,,175600|100|1000|1000|4500|30000|500|400|500|2000|500|5200|5000|1000|1000|6000|300|3000|18800|800|500|3500|1000|200|2000|2800|1200|600|1000|1000|15000|5000|300|2400|600|200|100|1000|300|1000|2600|400|500|1700|2200|300|1000|10400|1000|900,]
	// [2cn_sz002342_0=2917644|15:00:18.870|6.520|600|3912.000|4034422|3999218|2|7,2917645|15:00:18.870|6.520|3000|19560.000|4034428|3999218|2|7,2917646|15:00:18.870|6.520|1000|6520.000|4034445|3999218|2|7,2917647|15:00:18.870|6.520|12300|80196.000|4034460|3999218|2|7,2917648|15:00:18.870|6.520|1900|12388.000|4034460|3999298|2|7,2917649|15:00:18.870|6.520|700|4564.000|4034460|3999452|2|7,2917650|15:00:18.870|6.520|2100|13692.000|4034460|4000213|2|7,2917651|15:00:18.870|6.520|1000|6520.000|4034460|4000631|2|7,2917652|15:00:18.870|6.520|5000|32600.000|4034460|4000659|2|7,2917653|15:00:18.870|6.520|5000|32600.000|4034460|4000861|2|7,2917654|15:00:18.870|6.520|100|652.000|4034460|4001408|2|7,2917655|15:00:18.870|6.520|500|3260.000|4034460|4034238|2|7,2917656|15:00:18.870|6.520|500|3260.000|4034460|4034240|2|7,2917657|15:00:18.870|6.520|3000|19560.000|4034460|4034244|2|7,2917658|15:00:18.870|6.520|500|3260.000|4034460|4034246|2|7,2917659|15:00:18.870|6.520|600|3912.000|4034460|4034248|2|7,2917660|15:00:18.870|6.520|200|1304.000|4034460|4034265|2|7,2917661|15:00:18.870|6.520|73900|481828.000|4034460|4034271|2|7,2917662|15:00:18.870|6.520|300|1956.000|4034464|4034271|2|7,2917663|15:00:18.870|6.520|5000|32600.000|4034472|4034271|2|7,2917664|15:00:18.870|6.520|900|5868.000|4034481|4034271|2|7,2917665|15:00:18.870|6.520|300|1956.000|4034494|4034271|2|7,2917666|15:00:18.870|6.520|1000|6520.000|4034496|4034271|2|7,2917667|15:00:18.870|6.520|3000|19560.000|4034502|4034271|2|7,2917668|15:00:18.870|6.520|500|3260.000|4034512|4034271|2|7,2917669|15:00:18.870|6.520|2300|14996.000|4034513|4034271|2|7,2917670|15:00:18.880|6.520|1000|6520.000|4034531|4034271|2|7,2917671|15:00:18.880|6.520|1100|7172.000|4034534|4034271|2|7,2917672|15:00:18.880|6.520|100|652.000|4034561|4034271|2|7,2917673|15:00:18.880|6.520|2800|18256.000|4034569|4034271|2|7,2917674|15:00:18.880|6.520|400|2608.000|4034572|4034271|2|7,2917675|15:00:18.880|6.520|800|5216.000|4034579|4034271|2|7,2917676|15:00:18.880|6.520|600|3912.000|4034584|4034271|2|7,2917677|15:00:18.880|6.520|4000|26080.000|4034585|4034271|2|7,2917678|15:00:18.880|6.520|1000|6520.000|4034587|4034271|2|7,2917679|15:00:18.880|6.520|500|3260.000|4034590|4034271|2|7,2917680|15:00:18.880|6.520|3000|19560.000|4034591|4034271|2|7,2917681|15:00:18.880|6.520|2200|14344.000|4034598|4034271|2|7,2917682|15:00:18.880|6.520|1000|6520.000|4034601|4034271|2|7,2917683|15:00:18.880|6.520|10000|65200.000|4034603|4034271|2|7,2917684|15:00:18.880|6.520|3000|19560.000|4034604|4034271|2|7,2917685|15:00:18.880|6.520|7700|50204.000|4034612|4034271|2|7,2917686|15:00:18.880|6.520|5900|38468.000|4034617|4034271|2|7,2917687|15:00:18.880|6.520|1000|6520.000|4034624|4034271|2|7,2917688|15:00:18.880|6.520|300|1956.000|4034625|4034271|2|7,2917689|15:00:18.880|6.520|1800|11736.000|4034630|4034271|2|7,2917690|15:00:18.880|6.520|500|3260.000|4034641|4034271|2|7,2917691|15:00:18.880|6.520|900|5868.000|4034646|4034271|2|7,2917692|15:00:18.880|6.520|800|5216.000|4034647|4034271|2|7,2917693|15:00:18.880|6.520|400|2608.000|4034649|4034271|2|7,2917694|15:00:18.880|6.520|5000|32600.000|4034650|4034271|2|7,2917695|15:00:18.880|6.520|1000|6520.000|4034651|4034271|2|7,2917696|15:00:18.880|6.520|500|3260.000|4034658|4034271|2|7,2917697|15:00:18.880|6.520|10000|65200.000|4034661|4034271|2|7,2917698|15:00:18.880|6.520|600|3912.000|4034663|4034271|2|7,2917699|15:00:18.880|6.520|1600|10432.000|4034665|4034271|2|7,2917700|15:00:18.880|6.520|2000|13040.000|4034667|4034271|2|7,2917701|15:00:18.880|6.520|3000|19560.000|4034670|4034271|2|7,2917702|15:00:18.880|6.520|3000|19560.000|4034671|4034271|2|7,2917703|15:00:18.880|6.520|100|652.000|4034673|4034271|2|7,2917704|15:00:18.880|6.520|700|4564.000|4034674|4034271|2|7,2917705|15:00:18.880|6.520|3000|19560.000|4034678|4034271|2|7,2917706|15:00:18.880|6.520|300|1956.000|4034685|4034271|2|7,2917707|15:00:18.880|6.520|300|1956.000|4034686|4034271|2|7,2917708|15:00:18.880|6.520|900|5868.000|4034688|4034271|2|7,2917709|15:00:18.880|6.520|500|3260.000|4034696|4034271|2|7]
	// [2cn_sz002342_1=2917710|15:00:18.880|6.520|500|3260.000|4034698|4034271|2|7,2917910|15:00:18.890|6.520|200|1304.000|4034704|4034271|2|7,2917911|15:00:18.890|6.520|20500|133660.000|4034710|4034271|2|7,2917912|15:00:18.890|6.520|2300|14996.000|4034712|4034271|2|7,2917913|15:00:18.890|6.520|200|1304.000|4034712|4034284|2|7,2917914|15:00:18.890|6.520|1900|12388.000|4034712|4034289|2|7,2917915|15:00:18.890|6.520|1200|7824.000|4034712|4034296|2|7,2917916|15:00:18.890|6.520|3800|24776.000|4034733|4034296|2|7,2917917|15:00:18.890|6.520|800|5216.000|4034733|4034301|2|7,2917918|15:00:18.890|6.520|23900|155828.000|4034733|4034324|2|7,2917919|15:00:18.890|6.520|2000|13040.000|4034738|4034324|2|7,2917920|15:00:18.890|6.520|100|652.000|4034742|4034324|2|7,2917921|15:00:18.890|6.520|300|1956.000|4034752|4034324|2|7,2917922|15:00:18.890|6.520|5000|32600.000|4034755|4034324|2|7,2917923|15:00:18.890|6.520|200|1304.000|4034765|4034324|2|7,2917924|15:00:18.890|6.520|2400|15648.000|4034766|4034324|2|7,2917925|15:00:18.890|6.520|3000|19560.000|4034769|4034324|2|7,2917926|15:00:18.890|6.520|10000|65200.000|4034778|4034324|2|7,2917927|15:00:18.890|6.520|4500|29340.000|4034804|4034324|2|7,2917928|15:00:18.890|6.520|300|1956.000|4034806|4034324|2|7,2917929|15:00:18.890|6.520|900|5868.000|4034809|4034324|2|7,2917930|15:00:18.890|6.520|1700|11084.000|4034812|4034324|2|7,2917931|15:00:18.890|6.520|1500|9780.000|4034815|4034324|2|7,2917932|15:00:18.890|6.520|1000|6520.000|4034817|4034324|2|7,2917933|15:00:18.890|6.520|1800|11736.000|4034822|4034324|2|7,2917934|15:00:18.890|6.520|1000|6520.000|4034826|4034324|2|7,2917935|15:00:18.890|6.520|1300|8476.000|4034839|4034324|2|7,2917936|15:00:18.890|6.520|1000|6520.000|4034846|4034324|2|7,2917937|15:00:18.890|6.520|800|5216.000|4034858|4034324|2|7,2917938|15:00:18.890|6.520|1100|7172.000|4034864|4034324|2|7,2917939|15:00:18.890|6.520|300|1956.000|4034879|4034324|2|7,2917940|15:00:18.890|6.520|500|3260.000|4034887|4034324|2|7,2917941|15:00:18.890|6.520|1000|6520.000|4034900|4034324|2|7,2917942|15:00:18.890|6.520|1000|6520.000|4034902|4034324|2|7,2917943|15:00:18.890|6.520|200|1304.000|4034904|4034324|2|7,2917944|15:00:18.890|6.520|6600|43032.000|4034914|4034324|2|7,2917945|15:00:18.890|6.520|300|1956.000|4034923|4034324|2|7,2917946|15:00:18.890|6.520|100|652.000|4034925|4034324|2|7,2917947|15:00:18.890|6.520|1000|6520.000|4034929|4034324|2|7,2917948|15:00:18.890|6.520|4700|30644.000|4034938|4034324|2|7,2917949|15:00:18.890|6.520|1400|9128.000|4034941|4034324|2|7,2917950|15:00:18.890|6.520|9800|63896.000|4034943|4034324|2|7,2917951|15:00:18.890|6.520|2500|16300.000|4034944|4034324|2|7,2917952|15:00:18.890|6.520|2000|13040.000|4034952|4034324|2|7,2917953|15:00:18.890|6.520|5000|32600.000|4034965|4034324|2|7,2917954|15:00:18.890|6.520|1600|10432.000|4034970|4034324|2|7,2917955|15:00:18.890|6.520|500|3260.000|4034977|4034324|2|7,2917956|15:00:18.890|6.520|1800|11736.000|4034982|4034324|2|7,2917957|15:00:18.890|6.520|500|3260.000|4034991|4034324|2|7,2917958|15:00:18.890|6.520|2000|13040.000|4034997|4034324|2|7,2917959|15:00:18.890|6.520|1600|10432.000|4035013|4034324|2|7,2917960|15:00:18.890|6.520|100|652.000|4035025|4034324|2|7,2917961|15:00:18.890|6.520|500|3260.000|4035052|4034324|2|7,2917962|15:00:18.890|6.520|5600|36512.000|4035054|4034324|2|7,2917963|15:00:18.890|6.520|5000|32600.000|4035055|4034324|2|7,2917964|15:00:18.890|6.520|100|652.000|4035056|4034324|2|7,2917965|15:00:18.890|6.520|10000|65200.000|4035060|4034324|2|7,2917966|15:00:18.890|6.520|2000|13040.000|4035062|4034324|2|7,2917967|15:00:18.890|6.520|200|1304.000|4035067|4034324|2|7,2917968|15:00:18.890|6.520|400|2608.000|4035075|4034324|2|7,2917969|15:00:18.890|6.520|5000|32600.000|4035088|4034324|2|7,2917970|15:00:18.890|6.520|100|652.000|4035089|4034324|2|7,2917971|15:00:18.890|6.520|1400|9128.000|4035094|4034324|2|7,2917972|15:00:18.890|6.520|200|1304.000|4035098|4034324|2|7,2917973|15:00:18.890|6.520|300|1956.000|4035105|4034324|2|7,2917974|15:00:18.890|6.520|4500|29340.000|4035111|4034324|2|7]
	// [sz002342_i=A,jlsj,0.0340,0.0274,0.0310,2.5067,1950.4214,96000,82628.0625,82628.0625,0,CNY,0.3224,0.2644,24.0000,1,1.2600,7.2035,0.3017]
	// [sz002342=巨力索具,6.30,6.34,6.52,6.54,6.28,6.51,6.52,32306319,208605766.61,461190,6.51,290650,6.50,147600,6.49,144600,6.48,65900,6.47,637200,6.52,310792,6.53,397700,6.54,519600,6.55,321716,6.56,2015-10-15,15:05:53,00]
	// [sys_nxkey=2cn_sh600650_l,2cn_sz002342_l]
    //转换成一只股票一个字符串。
	private void split2Line(String msg, Map<String, String> tmp_msgs)
	{
		try
		{
			tmp_msgs.clear();

			ByteArrayInputStream in = new ByteArrayInputStream(msg.getBytes());
			BufferedReader dr = new BufferedReader(new InputStreamReader(in));
			String line = dr.readLine();
			while (line != null)
			{
				String[] str = line.split("=");
				if (str.length != 2)
				{
					return;
				}
				String key = str[0];
				String value = str[1];
				tmp_msgs.put(key, value);
				line = dr.readLine();
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}

	}

	public void onConnect()
	{
		if (preFecher != null)
		{
			preFecher.close();
		}
	}

	public void parseMessage(String msg)
	{
		this.level2_handler.onMessage(msg);
//		//System.out.println("接收到数据"+msg);
//		Map<String, String> tmp_msgs = new HashMap<>();
//		split2Line(msg, tmp_msgs);
//		Map<String, Object> datas = new HashMap<>();
//
//		for (String sym : symbols)
//		{
//			String key = null;
//			String value = null;
//
//			key = "2cn_" + datautils.generateCode(sym);// 实时行情
//			value = tmp_msgs.get(key);
//			if (value != null)
//			{
//				parseLevel2_10Top(sym, value, datas);
//			}
//
//			key = "2cn_" + datautils.generateCode(sym) + "_orders"; // 50笔委托单
//			value = tmp_msgs.get(key);
//			if (value != null)
//			{
//				parseLevel2_50orders(sym, value, datas);
//			}
//
//			key = "2cn_" + datautils.generateCode(sym) + "_0";// 逐笔
//			value = tmp_msgs.get(key);
//			if (value != null)
//			{
//				key = "2cn_" + datautils.generateCode(sym) + "_1";// 逐笔
//				value += "," + tmp_msgs.get(key);
//				parseLevel2_ZB(sym, value, datas);
//			}
//		}
//
//		for (String sym : indexsymbols)
//		{
//			String key = null;
//			String value = null;
//
//			key = "2cn_" + datautils.generateCode(sym);// 实时行情
//			value = tmp_msgs.get(key);
//			if (value != null)
//			{
//				parseLevel2_Indexinfo(sym, value, datas);
//			}
//		}
//
//		if (level2_handler == null)
//			return;
//
//		level2_handler.onLevel2(fetch_type, datas);
	}

	private void parseLevel2_Indexinfo(String sym, String value, Map<String, Object> datas)
	{
		try
		{
			// System.out.println(sym +
			// ",实时行情:---------------------------------");
			String[] v = value.split(",");
			if (v.length < 12)
				return;

			// for (int i = 0; i < v.length; i++)
			// {
			// String item = v[i];
			// System.out.println("[" + i + "]=" + item);
			// }

			SimpleLevel l = new SimpleLevel();

			l.symbol = sym;
			l.name = v[0];
			l.time = Utils.strToDate(v[2] + " " + v[1]).getTime();
			l.price = Double.valueOf(v[7]);
			l.lastclose = Double.valueOf(v[3]);
			l.open = Double.valueOf(v[4]);
			l.high = Double.valueOf(v[5]);
			l.low = Double.valueOf(v[6]);
			// long zb = Long.valueOf(v[9]);// 总笔
			l.volume = Long.valueOf(v[10]);// 总量，手
			l.amount = Double.valueOf(v[11]);// 总额,元

			// l.print();

			datas.put(sym + "_index", l);

		} catch (NumberFormatException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void parseLevel2_10Top(String sym, String value, Map<String, Object> datas)
	{

		// System.out.println(sym + ",实时行情:---------------------------------");
		String[] v = value.split(",");
		try
		{
			if (v.length < 57)
				return;

			Level2 l = new Level2();
			l.name = v[0];
			l.time = Utils.strToDate(v[2] + " " + v[1]).getTime();
			l.price = Double.valueOf(v[7]);
			l.symbol = sym;

			l.lastclose = Double.valueOf(v[3]);
			l.open = Double.valueOf(v[4]);
			l.high = Double.valueOf(v[5]);
			l.low = Double.valueOf(v[6]);

			// long zb=Long.valueOf(v[9]);//总笔
			// long zl=Long.valueOf(v[10]);//总量，手

			for (int i = 0; i < 10; i++)
			{
				int sell_start = 46 + i;
				int buy_start = 26 + i;

				l.bid[i] = Double.valueOf(v[buy_start]);
				l.bidvol[i] = Long.valueOf(v[buy_start + 10]);

				l.ask[i] = Double.valueOf(v[sell_start]);
				l.askvol[i] = Long.valueOf(v[sell_start + 10]);
			}

			// for (int i = 9; i >= 0; i--)
			// {
			// System.out.println("卖 " + i + "\t" + l.ask[i] + "\t" +
			// (l.askvol[i]));
			// }
			// System.out.println("------------" + l.price +
			// "---------------------");
			// for (int i = 0; i < 10; i++)
			// {
			// System.out.println("买 " + i + "\t" + l.bid[i] + "\t" +
			// (l.bidvol[i]));
			// }

			datas.put(sym + "_level2", l);

		} catch (NumberFormatException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();

			for (int i = 0; i < v.length; i++)
			{
				String item = v[i];
				System.out.println("[" + i + "]=" + item);
			}
		}

	}

	private void parseLevel2_50orders(String sym, String value, Map<String, Object> datas)
	{

		// System.out.println(sym +
		// ",50笔委托单:---------------------------------");
		String[] v = value.split(",");
		try
		{
			Level2_50orderInfo info = new Level2_50orderInfo();
			info.symbol = sym;

			info.buy_price = Double.valueOf(v[2]);// 委托买一，价格6.66
			info.buy_count = Long.valueOf(v[3]);// 该价位上，总共，手
			info.buy_bi = Integer.valueOf(v[4]);// 该价位上，总笔
			info.sell_price = Double.valueOf(v[5]);// 委托卖一，价格
			info.sell_count = Long.valueOf(v[6]);
			info.sell_bi = Integer.valueOf(v[7]);

			if (info.sell_bi > 0)
			{
				String[] sellvol_str = v[10].split("\\|");
				info.sellvol = new long[sellvol_str.length];
				for (int i = 0; i < info.sellvol.length; i++)
				{
					info.sellvol[i] = Long.valueOf(sellvol_str[i]);
				}

			}

			if (info.buy_bi > 0)
			{
				String[] buyvol_str = v[8].split("\\|");
				info.buyvol = new long[buyvol_str.length];
				for (int i = 0; i < info.buyvol.length; i++)
				{
					info.buyvol[i] = Long.valueOf(buyvol_str[i]);
				}
			}
			// info.print();
			datas.put(sym + "_level2_order", info);

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			for (int i = 0; i < v.length; i++)
			{
				String item = v[i];
				System.out.println("[" + i + "]=" + item);
			}
		}

	}

	private void parseLevel2_ZB(String sym, String value, Map<String, Object> datas)
	{

		// System.out.println(sym + ",逐笔:---------------------------------");
		String[] v = value.split(",");
		try
		{
			String date = Utils.getTodayStr();
			List<ZB> zbs = new ArrayList<>();

			for (int i = 0; i < v.length; i++)
			{
				String[] item = v[i].split("\\|");
				if (item.length < 9)
					continue;

				ZB zb = new ZB();
				zb.symbol = sym;
				zb.sortid = Long.valueOf(item[0]);
				String time = date + " " + item[1];
				zb.time = Utils.longstrToDate(time).getTime();
				zb.price = Double.valueOf(item[2]);
				zb.vol = Long.valueOf(item[3]);
				zb.op = item[7].equals("2") ? ZB.OP_BUY : (item[7].equals("0") ? ZB.OP_SELL : ZB.OP_PING);

				zbs.add(zb);

			}

			datas.put(sym + "_level2_zb", zbs);

		} catch (NumberFormatException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			for (int i = 0; i < v.length; i++)
			{
				String item = v[i];
				System.out.println("[" + i + "]=" + item);
			}
		}

	}
    
	/**
	 *    获取level2的校验数据。
	 * @param symbols
	 * @param Indexsymbols
	 * @param foreceAuthen
	 * @return
	 */
	public String getLevel2AuthenCodeInfo(List<String> symbols, List<String> Indexsymbols, boolean foreceAuthen)
	{
		try
		{
			String query = "A_hq";
			String ip = datautils.getClientip();
			String list = Config.makeLevel2QueryString(symbols, Indexsymbols,this.fetch_type);

			int kick = 1;

			double random = Math.random();
			Map<String, String> map = new HashMap<String, String>();
			map.put("query", query);
			map.put("ip", ip);
			map.put("_", random + "");
			map.put("list", list);
//			if (foreceAuthen)
//			{
				map.put("kick", kick + "");
//			}

			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("https").setHost("current.sina.com.cn").setPath("/auth/api/jsonp.php/var%20KKE_auth_3kl3Kx6qv=/AuthSign_Service.getSignCode").setParameters(para).build();
            //这个url像是订阅一组数据
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "current.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");
            //尝试3次
			for (int i = 0; i < 3; i++)
			{
				try
				{
					//发起请求。
					HttpRequestFutureTask<String> futur_ret = datautils.doHttpMethod(httpmethod);
					String ret = futur_ret.get();
					if (ret != null)
					{
						String callback = "var KKE_auth_3kl3Kx6qv=";
						//类似于要订阅一下，订阅成功的话，会返回var%20KKE_auth_3kl3Kx6qv=(({msg_code:1,result:"A1UDAYIDtwMDAypG.sqM7VkllVoodGsYlfLUnwgC",timeout:180}));
						//订阅失败的会返回异常
						String response = ret.substring(callback.length() + 4, ret.lastIndexOf(")") - 1);
						return response;
					}
				} catch (Exception e)
				{
					e.printStackTrace();
					System.out.println("level scrible list size:" + symbols.size());
					datautils.setLogined(false);
				}
			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

}
